document.addEventListener('DOMContentLoaded', () => {
    const downloadBtn = document.getElementById('downloadBtn');
    const statusDiv = document.getElementById('status');

    downloadBtn.addEventListener('click', async () => {
        statusDiv.textContent = '正在获取视频信息...';
        console.log('Popup: 开始获取视频信息');
        
        try {
            // 获取当前活动标签页
            const [tab] = await chrome.tabs.query({ 
                active: true, 
                currentWindow: true 
            });

            if (!tab.url.includes('douyin.com')) {
                statusDiv.textContent = '请在抖音页面使用此插件';
                return;
            }

            console.log('Popup: 当前标签页:', tab.url);

            // 方法1: 从content script获取视频信息
            let videoInfo = null;
            try {
                console.log('Popup: 尝试从content script获取视频信息');
                const response = await chrome.tabs.sendMessage(tab.id, { type: 'GET_VIDEO_INFO' });
                console.log('Popup: Content script原始响应:', response);
                
                // 检查是否有错误信息
                if (response && response.error) {
                    statusDiv.textContent = response.error;
                    console.log('Popup: Content script返回错误:', response.error);
                    return;
                }
                
                if (response && response.url) {
                    videoInfo = response;
                    console.log('Popup: Content script返回:', videoInfo);
                } else {
                    console.log('Popup: Content script未返回有效数据:', response);
                }
            } catch (e) {
                console.log('Popup: Content script通信失败:', e);
            }

            // 方法2: 如果content script失败，直接在页面执行脚本
            if (!videoInfo || !videoInfo.url) {
                console.log('Popup: 尝试直接执行脚本获取视频信息');
                try {
                    const results = await chrome.scripting.executeScript({
                        target: { tabId: tab.id },
                        function: extractVideoInfo
                    });
                    
                    if (results && results[0] && results[0].result && results[0].result.url) {
                        videoInfo = results[0].result;
                        console.log('Popup: 脚本执行结果:', videoInfo);
                    }
                } catch (e) {
                    console.error('Popup: 脚本执行失败:', e);
                }
            }

            // 方法3: 从background获取拦截的URL
            if (!videoInfo || !videoInfo.url) {
                console.log('Popup: 尝试从background获取拦截的URL，当前tab ID:', tab.id);
                try {
                    const response = await chrome.runtime.sendMessage({ type: 'GET_VIDEO_URLS' });
                    console.log('Popup: Background返回的URLs:', response);
                    if (response && response.urls && response.urls.length > 0) {
                        // 显示所有找到的URL用于调试
                        console.log('Popup: 所有拦截的URLs:', response.urls);
                        
                        // 过滤出有效的视频URL
                        const validUrls = response.urls.filter(url => {
                            const isValid = isValidVideoUrl(url);
                            console.log('Popup: URL验证结果:', url, isValid);
                            return isValid;
                        });
                        
                        console.log('Popup: 有效的视频URLs:', validUrls);
                        
                        if (validUrls.length > 0) {
                            videoInfo = {
                                url: validUrls[0],
                                title: '抖音视频',
                                timestamp: Date.now()
                            };
                            console.log('Popup: Background返回有效URL:', videoInfo);
                        } else {
                            console.log('Popup: Background中没有有效的视频URL');
                        }
                    } else {
                        console.log('Popup: Background未返回任何URL');
                    }
                } catch (e) {
                    console.error('Popup: Background通信失败:', e);
                }
            }

            if (!videoInfo || !videoInfo.url || !isValidVideoUrl(videoInfo.url)) {
                console.log('Popup: 视频信息检查失败:', {
                    hasVideoInfo: !!videoInfo,
                    hasUrl: videoInfo ? !!videoInfo.url : false,
                    url: videoInfo ? videoInfo.url : null,
                    isValid: videoInfo && videoInfo.url ? isValidVideoUrl(videoInfo.url) : false
                });
                
                // 提供更详细的错误信息
                let errorMessage = '下载失败: ';
                if (!videoInfo) {
                    errorMessage += '未找到视频信息，请确保在抖音视频页面使用';
                } else if (!videoInfo.url) {
                    errorMessage += '未找到视频URL，页面可能还在加载中';
                } else if (videoInfo.isPageUrl) {
                    errorMessage += '当前页面不是视频播放页面，请打开具体的视频页面';
                } else if (!isValidVideoUrl(videoInfo.url)) {
                    // 检查是否是抖音页面URL
                    if (videoInfo.url.startsWith('https://www.douyin.com/')) {
                        errorMessage += '当前页面不是视频播放页面，请打开具体的视频页面';
                    } else {
                        errorMessage += `视频URL格式不支持: ${videoInfo.url.substring(0, 50)}...`;
                    }
                } else {
                    errorMessage += 'Invalid video URL';
                }
                
                statusDiv.textContent = errorMessage;
                console.log('Popup: 未找到有效视频URL');
                return;
            }

            console.log('Popup: 最终获取到的视频信息:', videoInfo);
            
            // 清理URL
            const cleanUrl = cleanVideoUrl(videoInfo.url);
            console.log('Popup: 清理后的URL:', cleanUrl);
            
            if (!cleanUrl || !isValidVideoUrl(cleanUrl)) {
                statusDiv.textContent = '视频URL无效';
                return;
            }
            
            statusDiv.textContent = '正在下载...';
            console.log('Popup: 准备发送下载请求');
            console.log('Popup: 清理后的URL:', cleanUrl);
            console.log('Popup: 文件名:', videoInfo.title || '抖音视频');

            // 发送下载请求到background
            const downloadResponse = await chrome.runtime.sendMessage({
                action: 'DOWNLOAD_VIDEO',
                url: cleanUrl,
                filename: videoInfo.title || '抖音视频'
            });

            console.log('Popup: 下载响应:', downloadResponse);

            if (downloadResponse && downloadResponse.success) {
                statusDiv.textContent = '下载已开始！文件名: ' + downloadResponse.fileName;
                setTimeout(() => {
                    statusDiv.textContent = '点击下载视频';
                }, 5000);
            } else {
                const errorMsg = downloadResponse?.error || '未知错误';
                console.error('Popup: 下载失败详情:', errorMsg);
                statusDiv.textContent = '下载失败: ' + errorMsg;
                
                // 显示更详细的错误信息
                if (errorMsg.includes('网络错误') || errorMsg.includes('NETWORK_FAILED')) {
                    statusDiv.textContent += ' (网络连接问题)';
                } else if (errorMsg.includes('权限') || errorMsg.includes('PERMISSIONS')) {
                    statusDiv.textContent += ' (权限不足)';
                } else if (errorMsg.includes('Invalid URL')) {
                    statusDiv.textContent += ' (URL格式错误)';
                }
            }

        } catch (error) {
            console.error('Popup: 下载过程出错:', error);
            statusDiv.textContent = '下载失败: ' + error.message;
        }
    });
});

// 清理和解码视频URL
function cleanVideoUrl(url) {
    if (!url || typeof url !== 'string') return null;
    
    try {
        console.log('Popup: 开始清理URL:', url);
        
        // 移除首尾的引号、空格和反斜杠
        let cleanUrl = url.trim().replace(/^['"`\\]+|['"`\\]+$/g, '');
        
        // 解码Unicode转义字符
        cleanUrl = cleanUrl.replace(/\\u([0-9a-fA-F]{4})/g, (match, code) => {
            return String.fromCharCode(parseInt(code, 16));
        });
        
        // 解码常见的转义字符
        cleanUrl = cleanUrl.replace(/\\u0026/g, '&')
                          .replace(/\\u003d/g, '=')
                          .replace(/\\u003f/g, '?')
                          .replace(/\\u002f/g, '/')
                          .replace(/\\u003a/g, ':')
                          .replace(/\\\\/g, '\\')
                          .replace(/\\"/g, '"')
                          .replace(/\\'/g, "'");
        
        // 尝试URL解码
        try {
            if (cleanUrl.includes('%')) {
                cleanUrl = decodeURIComponent(cleanUrl);
            }
        } catch (e) {
            console.log('Popup: URL解码失败，使用原URL');
        }
        
        // 确保URL格式正确
        if (cleanUrl && !cleanUrl.startsWith('http')) {
            if (cleanUrl.startsWith('//')) {
                cleanUrl = 'https:' + cleanUrl;
            } else if (cleanUrl.startsWith('/')) {
                cleanUrl = 'https://www.douyin.com' + cleanUrl;
            }
        }
        
        console.log('Popup: URL清理结果:', url, '->', cleanUrl);
        return cleanUrl;
    } catch (e) {
        console.log('Popup: URL清理失败:', e);
        return url;
    }
}

// 视频URL验证函数
function isValidVideoUrl(url) {
    if (!url || typeof url !== 'string') return false;
    
    console.log('验证URL:', url);
    
    // 特殊处理：如果是抖音页面URL，直接返回false，因为这不是视频文件URL
    if (url.startsWith('https://www.douyin.com/') && !url.includes('video') && !url.includes('play')) {
        console.log('URL是抖音页面URL，不是视频文件URL');
        return false;
    }
    
    // 排除明确的非视频内容
    const excludePatterns = [
        '.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.ico',
        '.json', 'recommend/', 'feed/', 'search/', 'comment/', 'user/',
        'avatar', 'cover', 'data:', 'blob:'
    ];
    
    const lowerUrl = url.toLowerCase();
    for (const pattern of excludePatterns) {
        if (lowerUrl.includes(pattern)) {
            console.log('URL被排除，包含:', pattern);
            return false;
        }
    }
    
    // 检查明确的视频文件扩展名
    const videoExtensions = ['.mp4', '.webm', '.m4v', '.mov', '.avi', '.flv', '.m3u8'];
    for (const ext of videoExtensions) {
        if (lowerUrl.endsWith(ext) || lowerUrl.includes(ext + '?')) {
            console.log('URL匹配视频扩展名:', ext);
            return true;
        }
    }
    
    // 检查视频相关域名
    const videoDomains = [
        'douyinvod.com', 'bytedance.com', 'ixigua.com', 'byteimg.com',
        'tos.com', 'snssdk.com', 'volcengineapi.com', 'toutiaoapi.com'
    ];
    
    for (const domain of videoDomains) {
        if (lowerUrl.includes(domain)) {
            console.log('URL匹配视频域名:', domain);
            return true;
        }
    }
    
    // 检查视频相关路径和关键字
    const videoKeywords = [
        'video', 'play_addr', 'video_id', 'aweme/v1/play',
        'playAddr', 'downloadAddr'
    ];
    
    for (const keyword of videoKeywords) {
        if (lowerUrl.includes(keyword)) {
            console.log('URL匹配视频关键字:', keyword);
            return true;
        }
    }
    
    // 检查长URL中的视频关键词
    if (url.length > 50) {
        const longUrlKeywords = ['video', 'play', 'stream', 'flv', 'webm'];
        for (const keyword of longUrlKeywords) {
            if (lowerUrl.includes(keyword)) {
                console.log('长URL匹配视频关键字:', keyword);
                return true;
            }
        }
    }
    
    // 检查抖音特殊的加密视频URL（域名+长度>80）
    if (url.length > 80 && (lowerUrl.includes('volcengineapi.com') || lowerUrl.includes('toutiaoapi.com'))) {
        console.log('匹配抖音加密视频URL');
        return true;
    }
    
    // 检查长ID模式（可能是视频资源）
    if (/\/[a-zA-Z0-9_-]{15,}/.test(url)) {
        console.log('URL匹配长ID模式');
        return true;
    }
    
    console.log('URL验证失败');
    return false;
}

// 在页面中执行的视频信息提取函数
function extractVideoInfo() {
    console.log('页面脚本: 开始提取视频信息');
    
    const videoInfo = {
        url: null,
        title: '抖音视频',
        timestamp: Date.now()
    };
    
    // 视频URL验证函数
    function isValidVideoUrl(url) {
        if (!url || typeof url !== 'string') return false;
        
        // 排除明确的非视频URL
        if (url.includes('.json') || url.includes('recommend/') || 
            url.includes('feed/') || url.includes('search/') || 
            url.startsWith('data:') || url.startsWith('blob:')) {
            return false;
        }
        
        // 允许明确的视频文件
        if (url.endsWith('.mp4') || url.endsWith('.webm') || url.endsWith('.m4v') || 
            url.endsWith('.mov') || url.endsWith('.avi') || url.endsWith('.flv')) {
            return true;
        }
        
        // 允许包含video关键字的URL
        if (url.includes('video')) {
            return true;
        }
        
        // 允许抖音相关的媒体URL
        if (url.includes('douyinvod.com') || url.includes('/tos/') || 
            url.includes('bytedance.com') || url.includes('aweme')) {
            return true;
        }
        
        return false;
    }
    
    // 从script标签中提取视频URL
    function extractFromScriptTags() {
        const scripts = document.querySelectorAll('script');
        for (const script of scripts) {
            if (script.textContent) {
                const urlMatches = script.textContent.match(/https:\/\/[^"'\s]+/g);
                if (urlMatches) {
                    for (const url of urlMatches) {
                        // 验证URL
                        if (url && url.startsWith('http') && !url.includes('.json') && 
                            !url.includes('.jpg') && !url.includes('.jpeg') && 
                            !url.includes('.png') && !url.includes('.gif') && 
                            !url.includes('.webp') && !url.includes('avatar') && 
                            !url.includes('cover')) {
                            console.log('页面脚本: 从script标签找到URL:', url);
                            return url;
                        }
                    }
                }
            }
        }
        return null;
    }
    
    // 从页面HTML中提取视频URL
    function extractFromHTML() {
        const htmlContent = document.documentElement.outerHTML;
        
        // 查找视频URL模式
        const urlPatterns = [
            // 明确的视频文件
            /https:\/\/[^"'\s]+\.mp4[^"'\s]*/g,
            /https:\/\/[^"'\s]+\.m3u8[^"'\s]*/g,
            /https:\/\/[^"'\s]+\.webm[^"'\s]*/g,
            // 抖音相关域名的视频URL
            /https:\/\/[^"'\s]*douyinvod[^"'\s]*\.com[^"'\s]*\/[^"'\s]*video[^"'\s]*/g,
            /https:\/\/[^"'\s]*bytedance[^"'\s]*\.com[^"'\s]*\/[^"'\s]*play[^"'\s]*/g,
            /https:\/\/[^"'\s]*ixigua[^"'\s]*\.com[^"'\s]*\/[^"'\s]*video[^"'\s]*/g,
            /https:\/\/[^"'\s]*byteimg[^"'\s]*\.com[^"'\s]*\/[^"'\s]*video[^"'\s]*/g,
            /https:\/\/[^"'\s]*tos[^"'\s]*\.com[^"'\s]*\/[^"'\s]*video[^"'\s]*/g,
            // API接口模式
            /"video_url":\s*"([^"]+)"/g,
            /"play_url":\s*"([^"]+)"/g,
            /"playUrl":\s*"([^"]+)"/g,
            /"play_addr":\s*"([^"]+)"/g,
            // 包含video关键字但排除图片
            /"src":\s*"([^"]+video[^"]*\.mp4[^"]*)"/g
        ];
        
        for (const pattern of urlPatterns) {
            const matches = htmlContent.match(pattern);
            if (matches) {
                for (const match of matches) {
                    let url = match;
                    // 如果是JSON格式，提取URL值
                    if (match.includes('":')) {
                        const urlMatch = match.match(/"([^"]+)"/g);
                        if (urlMatch && urlMatch.length > 1) {
                            url = urlMatch[1].replace(/"/g, '');
                        }
                    }
                    
                    if (isValidVideoUrl(url)) {
                        console.log('页面脚本: 从HTML提取到有效URL:', url);
                        return url;
                    }
                }
            }
        }
        
        return null;
    }
    
    // 从video元素获取
    const videos = document.querySelectorAll('video');
    console.log('页面脚本: 找到video元素:', videos.length);
    
    for (const video of videos) {
        if (video.src && isValidVideoUrl(video.src)) {
            videoInfo.url = video.src;
            console.log('页面脚本: 从video元素获取有效URL:', videoInfo.url);
            break;
        }
    }
    
    // 从HTML内容中提取
    if (!videoInfo.url) {
        videoInfo.url = extractFromHTML();
    }
    
    // 从script标签中提取
    if (!videoInfo.url) {
        videoInfo.url = extractFromScriptTags();
    }
    
    // 从网络资源获取
    if (!videoInfo.url) {
        const resources = performance.getEntriesByType('resource');
        for (const resource of resources) {
            const url = resource.name;
            if (url && (url.includes('video') || url.includes('.mp4') || 
                       url.includes('douyinvod') || url.includes('ixigua') ||
                       url.includes('byteimg') || url.includes('tos') ||
                       url.includes('play_addr') || url.includes('aweme/v1/play'))) {
                if (!url.includes('.json') && !url.includes('recommend') && 
                    !url.includes('feed') && !url.includes('.jpg') && 
                    !url.includes('.jpeg') && !url.includes('.png') && 
                    !url.includes('.gif') && !url.includes('.webp') && 
                    !url.includes('avatar') && !url.includes('cover') && 
                    url.startsWith('http')) {
                    console.log('页面脚本: 从网络请求找到URL:', url);
                    videoInfo.url = url;
                    break;
                }
            }
        }
    }
    
    // 获取标题
    const titleSelectors = [
        '[data-e2e="video-desc"]',
        '.video-desc',
        'h1',
        '.title'
    ];
    
    for (const selector of titleSelectors) {
        const element = document.querySelector(selector);
        if (element && element.textContent.trim()) {
            videoInfo.title = element.textContent.trim().substring(0, 50);
            console.log('页面脚本: 获取到标题:', videoInfo.title);
            break;
        }
    }
    
    console.log('页面脚本: 最终视频信息:', videoInfo);
    return videoInfo;
}

// 监听来自background的错误消息
chrome.runtime.onMessage.addListener((message) => {
    if (message.type === 'DOWNLOAD_ERROR') {
        const statusDiv = document.getElementById('status');
        if (statusDiv) {
            statusDiv.textContent = '下载失败: ' + message.error;
        }
    }
});